package com.educhains.module.message.util;

/**
 * Created by YuRun on 2016/11/24.
 */

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

public class EmailUtils {

    private static final String subject = "EDU chains";

    public static boolean sendEmail(String fromEmail, String password, String context, String toEmail) throws Exception {
        EmailForSending mail = new EmailForSending(fromEmail, password);
        Map<String, String> map = new HashMap<String, String>();
        //map.put("mail.smtp.host", "smtp.qq.com");
        map.put("mail.smtp.host", "smtp.ym.163.com");
        map.put("mail.smtp.socketFactory.port", "465");
        map.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        mail.setProps(map);
        mail.initMessage();
        mail.setFrom(fromEmail);
        mail.setRecipients(toEmail);
        mail.setSubject(subject);
        mail.setDate(new Date());
        mail.setContent(context, "text/html;charset=utf-8");
        mail.sendMessage();
        return true;
    }

    //FIXME cannot be static class
    static class EmailForSending {
        private String username = null;
        private String password = null;
        private MimeMessage mimeMessage = null;
        private Properties props = null;
        private Multipart multipart = null;
        private BodyPart bodypart = null;

        //初始化username、password
        public EmailForSending(String username, String password) {
            this.username = username;
            this.password = password;
        }

        //配置属性
        public void setProps(Map<String, String> map) {
            props = new Properties();
            for (Map.Entry<String, String> entry : map.entrySet()) {
                props.setProperty(entry.getKey(), entry.getValue());
            }
        }

        //初始化session、mimeMessage
        public void initMessage() throws IOException, MessagingException {
            Session session = Session.getDefaultInstance(props);
            //session.setDebug(true); //设置获取 debug 信息
            mimeMessage = new MimeMessage(session);
        }

        //添加收件人
        public String setRecipients(String toEmail) throws AddressException, MessagingException {
//            if(recs.isEmpty()){
//                return "接收人地址为空!";
//            }
            mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
//            for(String str:recs){
//                mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(str));
//            }
            return "加入接收人地址成功!";
        }

        //发送邮件
        public void sendMessage() throws MessagingException {
            Transport.send(mimeMessage, username, password);
        }

        //设置邮件发送人的名字
        public void setFrom(String from) throws UnsupportedEncodingException, MessagingException {
            mimeMessage.setFrom(new InternetAddress(username, from));
        }

        //设置主题
        public void setSubject(String subject) throws MessagingException {
            mimeMessage.setSubject(subject);
        }

        //设置日期
        public void setDate(Date date) throws MessagingException {
            mimeMessage.setSentDate(new Date());
        }

        //设置邮件文本内容
        public void setText(String text) throws MessagingException {
            mimeMessage.setText(text);
        }

        //设置邮件头部
        public void setHeader(String arg0, String arg1) throws MessagingException {
            mimeMessage.setHeader(arg0, arg1);
        }


        //设置发送邮件的基本参数
        public void setDefaultMessagePros(String sub, String text, String rec) throws MessagingException, UnsupportedEncodingException {
            mimeMessage.setSubject(sub);
            mimeMessage.setText(text);
            mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(rec));
            mimeMessage.setSentDate(new Date());
            mimeMessage.setFrom(new InternetAddress(username, username));
        }

        //设置附件<添加多附件>
        public void setMultiparts(ArrayList<String> fileList) throws MessagingException, IOException {
            if (multipart == null) {
                multipart = new MimeMultipart();
            }
            for (String s : fileList) {
                multipart.addBodyPart(writeFiles(s));
            }
            mimeMessage.setContent(multipart);
        }

        //发送文本内容，设置编码方式
        public void setContent(String s, String type) throws MessagingException {
            if (multipart == null) {
                multipart = new MimeMultipart();
            }
            bodypart = new MimeBodyPart();
            bodypart.setContent(s, type);
            multipart.addBodyPart(bodypart);
            mimeMessage.setContent(multipart);
            mimeMessage.saveChanges();
        }

        //读取附件
        public BodyPart writeFiles(String filePath) throws IOException, MessagingException {
            File file = new File(filePath);
            if (!file.exists()) {
                throw new IOException("文件不存在!请确定文件路径是否正确");
            }
            bodypart = new MimeBodyPart();
            DataSource dataSource = new FileDataSource(file);
            bodypart.setDataHandler(new DataHandler(dataSource));
            //文件名要加入编码，不然出现乱码
            bodypart.setFileName(MimeUtility.encodeText(file.getName()));
            return bodypart;
        }
    }
}